package org.csu.mypetstore.api.utils.encrypt;

import org.csu.mypetstore.api.utils.encrypt.annotation.SensitiveField;
import org.springframework.util.DigestUtils;

import java.lang.reflect.Field;
import java.util.Objects;

class EncryptUtil {

    // 加密模式
    static final int ENCRYPT_MD5_MODE = 0;
    static final int ENCRYPT_AES_MODE = 1;

    static <T> T encrypt(Field[] declaredFields, T sensitiveObject, final int ENCRYPT_MODE) throws IllegalAccessException {
        for (Field field : declaredFields) {
            // 取出所有被SensitiveField注解的字段
            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
            if (Objects.nonNull(sensitiveField)) {
                field.setAccessible(true);
                Object targetProperty = field.get(sensitiveObject);
                if (targetProperty instanceof String) {
                    String value = (String) targetProperty;
                    String valueEncrypt;
                    if (ENCRYPT_MODE == ENCRYPT_MD5_MODE) {
                        valueEncrypt = EncryptUtil.MD5Encrypt(value);
                    } else if (ENCRYPT_MODE == ENCRYPT_AES_MODE) {
                        valueEncrypt = EncryptUtil.AESEncrypt(value);
                    } else {
                        valueEncrypt = value;
                    }
                    field.set(sensitiveObject, valueEncrypt);
                }
            }
        }
        return sensitiveObject;
    }

    // MD5解密功能暂时不需要
    static <T> T decrypt(T result) throws IllegalAccessException {
//        //取出resultType的类
//        Class<?> resultClass = result.getClass();
//        Field[] declaredFields = resultClass.getDeclaredFields();
//        for (Field field : declaredFields) {
//            //取出所有被EncryptDecryptField注解的字段
//            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
//            if (!Objects.isNull(sensitiveField)) {
//                field.setAccessible(true);
//                Object object = field.get(result);
//                //只支持String的解密
//                if (object instanceof String) {
//                    String value = (String) object;
//                    //对注解的字段进行逐一解密
//                    field.set(result, EncryptUtils.decrypt(value).replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1*****$2"));
//                }
//            }
//        }
        return result;
    }

    static String MD5Encrypt(String srcString) {
        return DigestUtils.md5DigestAsHex(srcString.getBytes());
    }

    // 可扩展
    static String AESEncrypt(String srcString) {
        return srcString;
    }
}
